package com.example.stujava.module.xiangxue.reflect.gson_type;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class GsonStu {
    public static void main(String[] args) {
        Response<Data> response = new Response<>(new Data(""), 200, "suc");
        Gson gson = new Gson();
        String json = gson.toJson(response);
        System.out.println(json);
        //Gson TypeToken
        Response<Data> resp = gson.fromJson(json, new TypeToken<Response<Data>>() {

        }.getType());
        System.out.println(resp.toString());
        //自定义TypeReference
        //Type type=new TypeReference<>()
        Response<Data> resp2 = gson.fromJson(json, new KcTypeReference<Response<Data>>() {

        }.getType2());
        System.out.println(resp2.toString());
        try {
          Type type=  new GenericCla<Math>(){

            }.getType();
            System.out.println(type.getTypeName());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }

    static class Response<T> {
        T data;
        int code;
        String msg;

        public Response(T data, int code, String msg) {
            this.data = data;
            this.code = code;
            this.msg = msg;
        }

        @Override
        public String toString() {
            return "Response{" +
                    "data=" + data +
                    ", code=" + code +
                    ", msg='" + msg + '\'' +
                    '}';
        }
    }

    static class Data {
        String result;

        public Data(String result) {
            this.result = result;
        }

        @Override
        public String toString() {
            return "Data{" +
                    "result='" + result + '\'' +
                    '}';
        }
    }

    //匿名内部类获取泛型信息

    public abstract static class GenericCla<T> {
        private final Type type;

        protected GenericCla() throws IllegalAccessException {
            Type superclass = getClass().getGenericSuperclass();
            if (!(superclass instanceof ParameterizedType)) {
                throw new IllegalAccessException("没有泛型信息");
            }
            type = ((ParameterizedType) superclass).getActualTypeArguments()[0];
        }

        public Type getType() {
            return type;
        }
    }
}


